package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.*;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.service.HTicketDeptOrderService;
import com.flea.hclv.util.HclvDictUtil;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgDeptMapper;
import com.flea.system.entity.OrgDept;
import com.flea.system.entity.WebDict;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @program: project
 * @description: 组团社购买门票记录
 * @author: shiliqiang
 * @create: 2018-12-31 10:18
 * @version: 1.0
 */
@Service
public class HTicketDeptOrderServiceImpl implements HTicketDeptOrderService {

    @Autowired
    private SpotTicketMapper spotTicketMapper;
    @Autowired
    private HTicketDeptOrderItemMapper hTicketDeptOrderItemMapper;
    @Autowired
    private HTicketDeptOrderMapper hTicketDeptOrderMapper;
    @Autowired
    private HTicketDeptPayInfoMapper hTicketDeptPayInfoMapper;
    @Autowired
    private OrgDeptMapper orgDeptMapper;
    @Autowired
    private HQrManageMapper hQrManageMapper;
    @Autowired
    private HSpotMapper hSpotMapper;

    @Override
    public ServerResponse<Map<String, Object>> selectByOrderId(String orderId) {
        List<Map<String, Object>> itemsMap = hTicketDeptOrderItemMapper.selectByOrderId(orderId);
        List<HTicketDeptOrderItem> items = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(itemsMap)) {
            for (Map<String, Object> map : itemsMap) {
                HTicketDeptOrderItem item = new HTicketDeptOrderItem();
                item.setTicketNum(map.get("ticketNum") == null ? 0 : (Integer) map.get("ticketNum"));
                item.setCurrentPrice(map.get("currentPrice") == null ? 0 : (Float) map.get("currentPrice"));
                String ticketType = map.get("ticketType") == null ? "" : (String) map.get("ticketType");
                item.setTicketType(HTicketSellOrderServiceImpl.getType(ticketType));
                items.add(item);
            }
        }

        HTicketDeptPayInfo payInfo = hTicketDeptPayInfoMapper.selectByOrderId(orderId);
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("items", items);
        dataMap.put("payInfo", payInfo);
        return ServerResponse.createBySuccess(dataMap);
    }

    @Override
    public ServerResponse<FleaPage<HTicketDeptOrder>> selectByDeptId(String deptUuid, int curPage, int pageSize, String spotName,String serviceType) {
        //获取组织类型

        List<HSpot> spots=null;
        if (!spotName.equals("")){
            StringBuilder sb = new StringBuilder();
            sb.append("%");
            sb.append(spotName);
            sb.append("%");
            spotName = String.valueOf(sb);
            spots = hSpotMapper.selectByName(spotName);
            if (CollectionUtils.isEmpty(spots)){
                return ServerResponse.createBySuccess(new FleaPage<HTicketDeptOrder>());
            }
        }
        RowBounds rowBounds = new RowBounds(curPage, pageSize);
        List<HTicketDeptOrder> orders = hTicketDeptOrderMapper.selectByDeptId(deptUuid,rowBounds,spots);
//        if (StringUtils.equals(HConstant.D_SERVICE_ORG_GROUP,serviceType)){
//
//        }else if (StringUtils.equals(HConstant.D_SERVICE_ORG_SUPPLIER,serviceType)){
//            orders =
//        }

        FleaPage<HTicketDeptOrder> orderFleaPage = new FleaPage<>(orders);


        List<HTicketDeptOrder> newList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(orders)){
            for (HTicketDeptOrder order : orders) {
                OrgDept dept = orgDeptMapper.selectByPrimaryKey(order.getgDeptId());
                if (dept==null){
                    continue;
                }
                order.setgDeptName(dept.getDeptName());
                dept = orgDeptMapper.selectByPrimaryKey(order.getzDeptId());
                order.setzDeptName(dept.getDeptName());
                newList.add(order);
            }
        }

        orderFleaPage.setCurPage(curPage);
        orderFleaPage.setPageSize(pageSize);
        orderFleaPage.setCurPageData(newList);
        return ServerResponse.createBySuccess(orderFleaPage);
    }

    @Override
    public ServerResponse<Map<String, Object>> selectBySpotIdAndDeptId(String spotTicketId, String userId) {
        SpotTicket spotTicket = spotTicketMapper.selectByPrimaryKey(spotTicketId);
        if (spotTicket == null) {
            return ServerResponse.createByErrorMessage("没有找到门票信息");
        }
        if (StringUtils.isEmpty(spotTicket.getUuid())) {
            return ServerResponse.createByErrorMessage("门票的景点ID为空");
        }
        if (StringUtils.isEmpty(spotTicket.getDeptId())) {
            return ServerResponse.createByErrorMessage("门票的部门ID为空");
        }
        String deptId = spotTicket.getDeptId();
        List<SpotTicket> data = spotTicketMapper.selectBySpotIdAndDeptId(spotTicket.getUuid(), deptId, null);
        if (CollectionUtils.isNotEmpty(data)) {
            for (SpotTicket entity : data) {
                if (StringUtils.isNotEmpty(entity.getType())) {
                    WebDict codeName = HclvDictUtil.getCodeName(entity.getType(), HConstant.D_SPOT_TICKET_TYPE);
                    if (codeName != null) {
                        entity.setTypeName(codeName.getDictName());
                    }
                }
            }
        }

        List<HQrManage> qrManages = hQrManageMapper.selectByDeptId(deptId);
        Map<String, Object> dataMap = Maps.newHashMap();
        dataMap.put("qrManages", qrManages);
        dataMap.put("ticketList", data);
        return ServerResponse.createBySuccess(dataMap);
    }

    @Override
    public ServerResponse<String> save(String model, String userId) throws Exception {
        //获取当前组团社id
        OrgDept dept = FleaOrgUtils.getCurrentUserDept(userId);
        if (dept == null) {
            return ServerResponse.createByErrorMessage("当前部门不能为空");
        }
        //创建订单记录
        HTicketDeptOrder order = new HTicketDeptOrder();
        String orderId = FleaStringUtils.getGenerateUUID();
        order.setId(orderId);
        order.setCreateUser(userId);
        order.setzDeptId(dept.getDeptUuid());
        JSONObject jsonObject = JSONObject.parseObject(model);
        List<HTicketDeptOrderItem> orderItems = JSON.parseArray(jsonObject.getString("item"), HTicketDeptOrderItem.class);
        HTicketDeptPayInfo hTicketDeptPayInfo = JSON.parseObject(jsonObject.getString("payinfo"), HTicketDeptPayInfo.class);
        String deptUuid = dept.getDeptUuid();
        String spotId = null;
        if (CollectionUtils.isNotEmpty(orderItems)) {
            //总价
            float totalPrice = 0;
            //总数量
            int totalNum = 0;
            String gDeptId = null;
            List<HTicketDeptOrderItem> newItems = Lists.newArrayList();
            for (HTicketDeptOrderItem item : orderItems) {
                String ticketId = item.getTicketId();
                if (StringUtils.isEmpty(ticketId)) {
                    throw new Exception("门票ID为空");
                }
                SpotTicket spotTicket = spotTicketMapper.selectByPrimaryKey(ticketId);
                if (spotTicket == null) {
                    throw new Exception("没有找到该门票信息");
                }
                if (StringUtils.isEmpty(spotTicket.getUuid())) {
                    throw new Exception("景点ID为空");
                }
                spotId = spotTicket.getUuid();
                Integer buyTicketNum = item.getTicketNum();
                if (null == buyTicketNum || buyTicketNum==0) {
                    continue;
                }
                String ticketType = spotTicket.getType();
                if (StringUtils.isEmpty(ticketType)) {
                    throw new Exception("门票类型为空");
                }
                //判断库存
                int stock = spotTicket.getNumber();
                if (stock == 0 || stock < buyTicketNum) {
                    WebDict codeName = HclvDictUtil.getCodeName(ticketType, HConstant.D_SPOT_TICKET_TYPE);
                    if (codeName != null) {
                        String typeName = codeName.getDictName();
                        throw new Exception(typeName + "库存不足");
                    }
                }

                Float currentPrice = spotTicket.getPrice();
                totalPrice += currentPrice * buyTicketNum;
                totalNum += buyTicketNum;


                //获取供应商ID
                gDeptId = spotTicket.getDeptId();

                String hTicketDeptPayItemId = FleaStringUtils.getGenerateUUID();
                item.setId(hTicketDeptPayItemId);
                item.setCreateUser(userId);

                item.setCurrentPrice(currentPrice);
                item.setTicketNum(buyTicketNum);
                //相当于设置订单号
                item.setTicketDeptOrderId(orderId);
                newItems.add(item);
                //创建组团社门票，或更新组团门票库存
//                String spotId = spotTicket.getUuid();
                List<SpotTicket> spotTicketList = spotTicketMapper.selectBySpotIdAndDeptId(spotTicket.getUuid(), deptUuid, ticketType);
                if (spotTicketList.size() == 1) {
                    //存在，更新组团门票库存
                    SpotTicket zDeptSpotTicket = spotTicketList.get(0);
                    int oldNum = zDeptSpotTicket.getNumber();
                    zDeptSpotTicket.setNumber(oldNum + buyTicketNum);
                    zDeptSpotTicket.setPrice(currentPrice);
                    zDeptSpotTicket.setSalePrice(spotTicket.getSalePrice());
                    int row = spotTicketMapper.updateByPrimaryKeySelective(zDeptSpotTicket);
                    if (row != 1) {
                        throw new Exception("更新组团社门票库存失败");
                    }
                } else if (CollectionUtils.isEmpty(spotTicketList)) {
                    this.createzDeptIdTicket(userId, deptUuid, buyTicketNum, spotTicket);
                } else {
                    throw new Exception("创建订单错误");
                }
                //更新供应商门票库存
                int updateStock = stock - buyTicketNum;
                if (updateStock < 0) {
                    throw new Exception(HTicketSellOrderServiceImpl.getType(ticketType) + "库存不足");
                }
                spotTicket.setNumber(updateStock);
                spotTicket.setModifyUser(userId);
                int row = spotTicketMapper.updateByPrimaryKeySelective(spotTicket);
                if (row != 1) {
                    throw new Exception("更新供应商库存失败");
                }
            }
            int row = hTicketDeptOrderItemMapper.insertBatch(newItems);
            if (row !=newItems.size()) {
                throw new Exception("批量创建组团社门票订单项失败");
            }
            if (gDeptId == null) {
                throw new Exception("供应商ID不能为空");
            }
            //设置订单供应供应商
            order.setgDeptId(gDeptId);
            order.setPayment(totalPrice);
            order.setQuantity(totalNum);
            order.setSpotId(spotId);
            row = hTicketDeptOrderMapper.insertSelective(order);
            if (row != 1) {
                throw new Exception("创建组团社门票订单失败");
            }
            //添加支付信息
            hTicketDeptPayInfo.setTicketDeptOrderId(orderId);
            hTicketDeptPayInfo.setId(FleaStringUtils.getGenerateUUID());
            hTicketDeptPayInfo.setCreateUser(userId);
            hTicketDeptPayInfo.setPayMoney(totalPrice);
            row = hTicketDeptPayInfoMapper.insertSelective(hTicketDeptPayInfo);
            if (row != 1)
                throw new Exception("添加支付信息失败");
            return ServerResponse.createBySuccessMessage("创建成功");
        } else {
            return ServerResponse.createByErrorMessage("创建失败");
        }
    }
    //创建组团社门票
    private void createzDeptIdTicket(String userId, String deptUuid, Integer buyTicketNum, SpotTicket spotTicket) throws Exception {
        //创建组团社门票
        SpotTicket entity = new SpotTicket();
        entity.setId(FleaStringUtils.getGenerateUUID());
        entity.setCreateUser(userId);
        entity.setDeptId(deptUuid);
        //设置组团社库存
        entity.setNumber(buyTicketNum);
        entity.setUuid(spotTicket.getUuid());
        entity.setType(spotTicket.getType());
        entity.setPrice(spotTicket.getPrice());
        entity.setSalePrice(spotTicket.getSalePrice());
        entity.setDescription(spotTicket.getDescription());
        int row = spotTicketMapper.insertSelective(entity);
        if (row != 1) {
            throw new Exception("创建组团社门票失败");
        }
    }

}
